To animate a sprite, you use the SetSpriteProperty function to change one or more of the sprite's properties, such as its matrix, layer, or image data. In addition to modifying a property, SetSpriteProperty invalidates the appropriate areas of the sprite's sprite world.
The SpriteWorldIdle function is responsible for redrawing a sprite world's invalid regions. Your application should call this function after modifying sprite properties to give the sprite world the opportunity to redraw.
Listing 0-3 shows the sample application's main function. It performs all of the application's initialization tasks, including initializing the sprite world and its sprites. It displays the window and loops until the user clicks the button in the window. To perform the animation, main calls the sample code function MoveSprites each time through the loop, to modify the properties of the sprites, and then calls SpriteWorldIdle to give the sprite world the opportunity to redraw its invalid areas.
// global variables
SpriteWorld gSpriteWorld = nil;
void main (void)
{
// ...
// initialize everything and create a window
// create a sprite world and the sprites in it
// show the window
// ...
CreateSpriteStuff(...);
while (!Button())
{
// animate the sprites
MoveSprites ();
SpriteWorldIdle (gSpriteWorld, 0, 0);
}
// ...
// dispose of the sprite world and its sprites
// shut down everything else
// ...
DisposeEverything();
}
The MoveSprites function, shown in Listing 0-4 , is responsible for modifying the properties of the sprites. For each sprite, the function calls SetSpriteProperty twice, once to change the sprite's matrix and once to change the sprite's image data pointer.
// constants
#define kNumSprites 4
#define kNumSpaceShipImages 24
// global variables
Rect gBounceBox;
Sprite gSprites[kNumSprites];
Rect gDestRects[kNumSprites];
Point gDeltas[kNumSprites];
short gCurrentImages[kNumSprites];
Handle gCompressedPictures[kNumSpaceShipImages];
void MoveSprites (void)
{
short i;
MatrixRecord matrix;
SetIdentityMatrix (&matrix);
// for each sprite
for (i = 0; i < kNumSprites; i++)
{
// modify the sprite's matrix
OffsetRect (&gDestRects[i], gDeltas[i].h, gDeltas[i].v);
if ( (gDestRects[i].right >= gBounceBox.right) ||
(gDestRects[i].left <= gBounceBox.left) )
gDeltas[i].h = -gDeltas[i].h;
if ( (gDestRects[i].bottom >= gBounceBox.bottom) ||
(gDestRects[i].top <= gBounceBox.top) )
gDeltas[i].v = -gDeltas[i].v;
matrix.matrix[2][0] = ((long)gDestRects[i].left << 16);
matrix.matrix[2][1] = ((long)gDestRects[i].top << 16);
SetSpriteProperty (gSprites[i], kSpritePropertyMatrix, &matrix);
// change the sprite's image
gCurrentImages[i]++;
if (gCurrentImages[i] >= (kNumSpaceShipImages * (i+1)))
gCurrentImages[i] = 0;
SetSpriteProperty (gSprites[i], kSpritePropertyImageDataPtr,
*gCompressedPictures[gCurrentImages[i] / (i+1)] );
}
}
| Previous | Chapter Contents | Chapter Top | Next |